/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.asu.cse360.service.impl;

import edu.asu.cse360.dto.StaffEfficiency;
import edu.asu.cse360.dto.StaffEfficiencyReport;
import edu.asu.cse360.model.Employee;
import edu.asu.cse360.model.ItemOrder;
import edu.asu.cse360.model.Restaurant;
import edu.asu.cse360.service.ItemOrderService;
import edu.asu.cse360.service.StaffReportService;
import edu.asu.cse360.service.util.ItemOrderEmployeeAccessor;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("staffReportService")
public class StaffReportServiceImpl implements StaffReportService {


    @Autowired
    private ItemOrderService itemOrderSvc;

    @Override
    public StaffEfficiencyReport getEfficiencyReport(String employeeType, Restaurant restaurant, DateTime startDate, DateTime endDate) {
        StaffEfficiencyReport report = null;
        List<ItemOrder> itemOrders = itemOrderSvc.getItemOrders(restaurant, startDate, endDate);
        if(Employee.TYPE_CHEF.equalsIgnoreCase(employeeType)){
            report = getEfficiencyReport(itemOrders, ItemOrderEmployeeAccessor.CHEF);
        }else{
            report = getEfficiencyReport(itemOrders, ItemOrderEmployeeAccessor.WAIT_PERSON);
        }
        report.setStartDate(startDate);
        report.setEndDate(endDate);
        return report;
    }

    private StaffEfficiencyReport getEfficiencyReport(List<ItemOrder> itemOrders, ItemOrderEmployeeAccessor employeeGetter) {
        List<StaffEfficiency> efficiencies = new ArrayList<StaffEfficiency>();
        Map<Employee, Integer> employeeFrequencyMap = new LinkedHashMap<Employee, Integer>();
        for(ItemOrder itemOrder : itemOrders){
            Employee employee = employeeGetter.getEmployee(itemOrder);
            if(employee == null) continue;
            Integer frequency = employeeFrequencyMap.get(employee);
            if(frequency == null){
                employeeFrequencyMap.put(employee, 1);
            }else{
                employeeFrequencyMap.put(employee, frequency + 1);
            }
        }
        for(Employee employee : employeeFrequencyMap.keySet()){
            Integer frequency = employeeFrequencyMap.get(employee);
            StaffEfficiency efficiency = new StaffEfficiency(employee, frequency);
            efficiencies.add(efficiency);
        }
        return new StaffEfficiencyReport(efficiencies);
    }

    

}
